package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ShopMapper shopMapper;


    /**
     * 根据查询商铺信息
     * @param id
     * @return
     */
    public Shop queryById(Long id) {

        //先查询缓存是否有数据
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(CACHE_SHOP_KEY + id);

        //有则在缓存中查询
        if (!entries.isEmpty()) {
            Shop shop = new Shop();
            BeanUtil.fillBeanWithMap(entries, shop, false);
            return shop;
        }

        //没有则查询数据库

        Shop shop = shopMapper.selectById(id);

        //如果没有数据，缓存空对象
        if (ObjectUtil.isEmpty(shop)){
            stringRedisTemplate.opsForHash().putAll(CACHE_SHOP_KEY + id, new HashMap<>());
            //过期时间2分钟
            stringRedisTemplate.expire(CACHE_SHOP_KEY + id, CACHE_NULL_TTL, TimeUnit.MINUTES);

            return null;
        }

        //添加数据到缓存
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(shop);

        Map<String, String> stringStringHashMap = stringObjectMap.entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        e -> e.getValue() == null ? "" : e.getValue().toString()
                ));

        stringRedisTemplate.opsForHash().putAll(CACHE_SHOP_KEY + id, stringStringHashMap);
        stringRedisTemplate.expire(CACHE_SHOP_KEY + id, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }

    /**
     * 更新商铺信息
     * @param shop
     * @return
     */
    @Transactional
    public Result updateShop(Shop shop) {

        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }


        LambdaUpdateWrapper<Shop> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Shop::getId, shop.getId());

        //更新数据
        shopMapper.update(shop,wrapper);

        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());

        return Result.ok();
    }

    @Override
    public void insert(Shop shop) {

        shopMapper.insert(shop);
        //更新缓存
        stringRedisTemplate.opsForHash().putAll(CACHE_SHOP_KEY + shop.getId(), BeanUtil.beanToMap(shop));

    }
}
